package com.example.task;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class TimeTask {

    private final ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    public TimeTask(ThreadPoolExecutor threadPoolExecutor) {
        this.threadPoolExecutor = threadPoolExecutor;
    }

    @PostConstruct
    public void init() {
        // 提交任务到线程池
        threadPoolExecutor.submit(this::printTimePeriodically);
    }

    private void printTimePeriodically() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                // 获取当前时间并格式化
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String currentTime = dateFormat.format(new Date());

                // 输出时间
                System.out.println("当前时间: " + currentTime);

                // 休眠1秒
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("任务被中断");
            }
        }
    }
}